package com.byzk.p2p.admin.base.util;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import com.byzk.p2p.admin.base.vo.PaymentRecordVo;
import com.byzk.p2p.front.vo.Calculator;
import com.byzk.p2p.front.vo.CalculatorVo;

public class BaseUtil {

	/**
	 * 充值
	 */
	public final static String CHONGZHI="CZ";
	
	/**
	 * 提现
	 */
	public final static String TIXIAN="TX";
	
	/**
	 * 资金流水
	 */
	public final static String ZIJINLIUSHUI="ZJLS";	

	/**
	 * 债权转让
	 */
	public final static String ZHAIQUAN="ZQ";	

	/**
	 * 投资
	 */
	public final static String TOUZI="SJ";	
	
	/**
	 * 根据类型生成单号
	 * @param type
	 * @return
	 */
	public static String generateCode(String type){
		return type+DateUtils.getFullFormat()+(new Random().nextInt(899)+100);
	}
	
	/**
	 * 还款方式算法
	 * @param type 还款方式（1一次性付款，2等额本息，3按期付息，到期还本）
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period  借款期限
	 * @param startDate 开始时间
	 * @param util 借款期限单位(月  or 天)
	 * @return
	 */
	public static List<PaymentRecordVo> generatePaymentRecord(Integer type,Double fund,Double percent,Integer period,Date startDate,String util){
		List<PaymentRecordVo> recordList=new ArrayList<PaymentRecordVo>();
		
		if(type==1){
			//TODO 总利息以及还款时间，添加借款期限的判断
			//总利息
			Double interest=0.00;
			if("MONTH".equals(util)){
				interest = StringToDoubletoFixed2(((percent/12)*period)*fund);
			}else{
				interest = StringToDoubletoFixed2(((percent/360)*period)*fund);
			}
			PaymentRecordVo record=new PaymentRecordVo();
			record.setId(1);
			record.setBalance(0.0);
			record.setFund(fund);
			record.setInterest(interest);
			record.setTotal(interest+fund);
			if("MONTH".equals(util)) {
				record.setPaymentDate(DateUtils.getMonthAfter(startDate, period));
			}else {
				record.setPaymentDate(DateUtils.getDayAfter(startDate, period));
			}
			recordList.add(record);
		}else if(type==3){
			if("MONTH".equals(util)){
				//月利息
				Double month_interest=StringToDoubletoFixed2((((percent/12)*period)*fund)/period);
				for(int i=0;i<period;i++){
					PaymentRecordVo record=new PaymentRecordVo();
					record.setId(i+1);
					record.setInterest(month_interest);
					if(i<period-1){
						record.setFund(0.0);
						record.setTotal(month_interest);
						record.setBalance(fund);
					}else{
						record.setFund(fund);
						record.setTotal(month_interest+fund);
						record.setBalance(0.0);
					}
					record.setPaymentDate(DateUtils.getMonthAfter(startDate, i+1));
					recordList.add(record);
				}				
			}else if("DAY".equals(util)){
				int count=period/30;
				Double month_interest=StringToDoubletoFixed2((((percent/12))*fund));
				for(int i=0;i<count;i++){
					PaymentRecordVo record=new PaymentRecordVo();
					record.setId(i+1);
					record.setInterest(month_interest);
					if(i<period-1){
						record.setFund(0.0);
						record.setTotal(month_interest);
						record.setBalance(fund);
					}else{
						record.setFund(fund);
						record.setTotal(month_interest+fund);
						record.setBalance(0.0);
					}
					record.setPaymentDate(DateUtils.getDayAfter(startDate, 30));
					recordList.add(record);
				}
			}

		}else if(type==2){
			//每月还贷本息
			Double temp_total=StringToDoubletoFixed2(fund*(percent/12)*Math.pow((1+(percent/12)),period)/(Math.pow(1+(percent/12),period)-1));
			Double item_total=0.0,item_fund=0.0,item_interest=0.0;
			for(int i=0;i<period;i++){
				PaymentRecordVo record=new PaymentRecordVo();
				//第n个月还贷利息
				Double temp_interest=StringToDoubletoFixed2((fund*(percent/12)-temp_total)*Math.pow((1+(percent/12)),i)+temp_total);
				//第n个月还贷本金
				Double temp_fund=temp_total-temp_interest;

				record.setId(i+1);
				if(i+1==period){
					record.setTotal(StringToDoubletoFixed2(((temp_fund+temp_interest)*period)-item_total));
					record.setFund(StringToDoubletoFixed2(fund-item_fund));
					record.setInterest(StringToDoubletoFixed2(((temp_fund+temp_interest)*period-fund)-item_interest));						
				}else{
					item_total+=temp_fund+temp_interest;
					item_fund+=temp_fund;
					item_interest+=temp_interest;					
					record.setTotal(StringToDoubletoFixed2(temp_total));
					record.setFund(StringToDoubletoFixed2(temp_fund));
					record.setInterest(StringToDoubletoFixed2(temp_interest));					
				}
				record.setBalance((temp_total*(period-(i+1))));
				record.setPaymentDate(DateUtils.getMonthAfter(startDate, i+1));
				recordList.add(record);
			}
		}
		return recordList;
	}
	
	/**
	 * 新手标还款方式算法(注：天标一次性还款)
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period  借款期限
	 * @param startDate 开始时间
	 * @return
	 */
	public static PaymentRecordVo generateNewsPaymentRecord(Double fund,Double percent,Integer period,Date startDate){
		//总利息
		Double interest=StringToDoubletoFixed2(((percent/12/30)*period)*fund);
		PaymentRecordVo record=new PaymentRecordVo();
		record.setId(1);
		record.setBalance(0.0);
		record.setFund(fund);
		record.setInterest(interest);
		record.setTotal(interest+fund);
		record.setPaymentDate(DateUtils.getDayAfter(startDate, period));
		return record;
	}
	
	
	/**
	 * 获取投资总利息
	 * @param type 还款方式（1一次性付款，2等额本息，3按期付息，到期还本）
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period  借款期限
	 * @param dateUtil  借款期单位
	 * @return
	 */
	public static Double getInterestByType(Integer type,Double fund,Double percent,Integer period,String dateUtil){
		if(type==2){
			Double temp_total=StringToDoubletoFixed2(fund*(percent/12)*Math.pow((1+(percent/12)),period)/(Math.pow(1+(percent/12),period)-1));
			return temp_total*period-fund;
		}else{
			if(type==1){//一次性还款
				//总利息
				//TODO 增加天标的判断
				if("MONTH".equals(dateUtil)) {
					Double interest=StringToDoubletoFixed2(((percent/12)*period)*fund);
					return interest;
				}else {
					//Double interest=StringToDoubletoFixed2(fund*percent/12/30*period);
					Double interest=StringToDoubletoFixed2(((percent/360)*period)*fund);
					return interest;
				}
			}else{
				//月利息
				Double month_interest=StringToDoubletoFixed2((((percent/12)*period)*fund)/period);
				return month_interest*period;
			}			
			
		}
	}
	
	/**
	 * 获取新手标投资总利息(注：天标一次性还款)
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period  借款期限
	 * @return
	 */
	public static Double getNewBorrowInterest(Double fund,Double percent,Integer period){
		return StringToDoubletoFixed2(((percent/12/30)*period)*fund);
	}
	
	/**
	 * 获取投资第N期的各项数据
	 * @param type 还款方式（1一次性付款，2等额本息，3按期付息，到期还本）
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period 借款期限
	 * @param period 借款期限单位
	 * @param startDate 借款日期
	 * @param index 第N期
	 * @return
	 */
	public static PaymentRecordVo getInterestByTypeAndIndex(Integer type,Double fund,Double percent,Integer period,String dateUtil,Integer index){
		PaymentRecordVo record=new PaymentRecordVo();
		
		if(type==1){
			//总利息
			//TODO 增加天标的判断
			if("MONTH".equals(dateUtil)) {
				Double interest=StringToDoubletoFixed2(((percent/12)*period)*fund);
				record.setId(1);
				record.setBalance(0.0);
				record.setFund(fund);
				record.setInterest(interest);
				record.setTotal(interest+fund);
			}else {
				Double interest=StringToDoubletoFixed2(((percent/360)*period)*fund);
				record.setId(1);
				record.setBalance(0.0);
				record.setFund(fund);
				record.setInterest(interest);
				record.setTotal(interest+fund);
			}
		}else if(type==3){
			//月利息
			Double month_interest=StringToDoubletoFixed2((((percent/12)*period)*fund)/period);
			record.setId(index);
			record.setInterest(month_interest);
			if(index==period){
				record.setFund(fund);
				record.setTotal(month_interest+fund);
				record.setBalance(0.0);
			}else{
				record.setFund(0.0);
				record.setTotal(month_interest);
				record.setBalance(0.0);
			}
		}else if(type==2){
			Double temp_total=StringToDoubletoFixed2(fund*(percent/12)*Math.pow((1+(percent/12)),period)/(Math.pow(1+(percent/12),period)-1));
			Double item_total=0.0,item_fund=0.0,item_interest=0.0;
			for(int i=0;i<period;i++){
				//第n个月还贷利息
				Double temp_interest=StringToDoubletoFixed2((fund*(percent/12)-temp_total)*Math.pow((1+(percent/12)),i)+temp_total);
				//第n个月还贷本金
				Double temp_fund=temp_total-temp_interest;
				//Double temp_fund=StringToDoubletoFixed2(fund*(percent/12)*Math.pow((1+(percent/12)),i)/(Math.pow(1+(percent/12),period)-1));
				//Double temp_interest=temp_total-temp_fund;

				record.setId(i+1);
				if(i+1==period){
					record.setTotal(StringToDoubletoFixed2(((temp_fund+temp_interest)*period)-item_total));
					record.setFund(StringToDoubletoFixed2(fund-item_fund));
					record.setInterest(StringToDoubletoFixed2(((temp_fund+temp_interest)*period-fund)-item_interest));
					record.setBalance((temp_total*(period-(i+1))));
				}else{
					item_total+=temp_fund+temp_interest;
					item_fund+=temp_fund;
					item_interest+=temp_interest;					
					record.setTotal(StringToDoubletoFixed2(temp_total));
					record.setFund(StringToDoubletoFixed2(temp_fund));
					record.setInterest(StringToDoubletoFixed2(temp_interest));
					record.setBalance((temp_total*(period-(i+1))));
				}
				
				if(index==i+1){
					break;
				}
			}
		}
		
		return record;
	}
	
	/**
	 * 获取新手标投资还款记录(注：天标一次性还款)
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period 借款期限
	 * @param startDate 借款日期
	 * @return
	 */
	public static PaymentRecordVo getInterest(Double fund,Double percent,Integer period){
		PaymentRecordVo record=new PaymentRecordVo();
		//总利息
		Double interest=StringToDoubletoFixed2(((percent/12/30)*period)*fund);
		record.setId(1);
		record.setBalance(0.0);
		record.setFund(fund);
		record.setInterest(interest);
		record.setTotal(interest+fund);
		return record;
	}
	
	/**
	 * double保留两位小树
	 * @param number
	 * @return
	 */
	public static Double StringToDoubletoFixed2(double number){
		BigDecimal  b =new BigDecimal(number);  
		double f1 =b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();  
		return f1;
	}
	
	/**
	 * 抽奖算法
	 * @param args
	 */
	public static Integer lottery(){
		return new Random().nextInt(1000)+1;
	}
	
	
	/**
	 * 获取投资总利息
	 * @param amount 投资总额
	 * @param percent 年利率
	 * @param deadline 借款期限
	 * @param dateUtil 借款期限单位("DAY" 或 "MONTH")
	 * @return
	 */
	public static Double getInvestTotalInterest(Double amount,Double percent,Integer deadline,String dateUtil){
		Double interest = 0.00;
		if("MONTH".equals(dateUtil)){
			interest = amount * (percent/12) * deadline;
		}else{
			interest = amount * (percent/360) * deadline;
		}
		return interest;
	}
	
	/**
	 * 获取投资总利息
	 * @param type 还款方式（1一次性付款，2等额本息，3按期付息，到期还本）
	 * @param fund 借款金额
	 * @param percent 年化率
	 * @param period  借款期限
	 * @return
	 */
	public static Double getTotalMoneyByType(Integer type,Double fund,Double percent,Integer period ,String dateUtil){
		if(type==3){
			Double temp_total=StringToDoubletoFixed2(fund*(percent/12)*Math.pow((1+(percent/12)),period)/(Math.pow(1+(percent/12),period)-1));
			return temp_total*period-fund;
		}else{
			if(type==2){
				//总利息
				Double interest=StringToDoubletoFixed2(((percent/12)*period)*fund);
				return interest;
			}else{
				//月利息
				Double month_interest=StringToDoubletoFixed2((((percent/12)*period)*fund)/period);
				return month_interest*period;
			}			
			
		}
	}
	
	public static CalculatorVo calculator(CalculatorVo vo){
		CalculatorVo cal = new CalculatorVo();
		String periodUnit = vo.getPeriodUnit();
		DecimalFormat df = new DecimalFormat("#.00");
		if("month".equals(periodUnit) || "MONTH".equals(periodUnit)){
			//一次性还款
			if(vo.getInterestMethod() == 1){
				List<Calculator> list = new ArrayList<Calculator>();
				Calculator cal1 = new Calculator();
				cal1.setIndex(1);
				cal1.setTotleAmount(df.format(vo.getMoney()*vo.getYearRate()/12/100*vo.getPeriod()+vo.getMoney()));
				cal1.setTotleMoney(df.format(vo.getMoney()));
				cal1.setInterest(df.format(vo.getMoney()*vo.getYearRate()/12/100*vo.getPeriod()));
				cal1.setIncome(df.format(vo.getMoney()*vo.getYearRate()/12/100*vo.getPeriod()));
				cal1.setResidualAmount("0.00");
				cal1.setResidualInterest("0.00");
				list.add(cal1);
				cal.setList(list);
				//回收总金额
				cal.setAmount(df.format(vo.getMoney()*vo.getYearRate()/12/100*vo.getPeriod()+vo.getMoney()));
				//月利率
				cal.setRate(df.format(vo.getYearRate()/12));
				//总回收利息
				cal.setTotleInterest(df.format(vo.getMoney()*vo.getYearRate()/12/100*vo.getPeriod()));
				cal.setPeriod(vo.getPeriod());
				cal.setPeriodUnit(vo.getPeriodUnit());
			}
//			//等额本金
//			if(vo.getInterestMethod() == 2){
//				Double totleTenderMonet=0.00;//累计还款金额
//				Double totleInterest = 0.00;//累计还款利息
//				List<Calculator> list = new ArrayList<Calculator>();
//				for(int i=0;i<vo.getPeriod();i++){
//					Calculator cal1 = new Calculator();
//					//每月还款金额
//					Double tenderAmount = (vo.getMoney()/vo.getPeriod())+(vo.getMoney()-totleTenderMonet)*vo.getYearRate()/12/100;
//					totleTenderMonet +=  tenderAmount;
//					Double tenderInterest = (vo.getMoney()-vo.getMoney()/vo.getPeriod()*i)*vo.getYearRate()/12/100;
//					totleInterest += tenderInterest;
//					cal1.setIndex(i+1);
//					cal1.setTotleAmount(df.format(tenderAmount));
//					cal1.setTotleMoney(df.format(vo.getMoney()/vo.getPeriod()));
//					cal1.setInterest(df.format(tenderInterest));
//					cal1.setIncome(df.format(tenderInterest));
//					cal1.setResidualAmount(df.format(vo.getMoney()-vo.getMoney()/vo.getPeriod()*(i+1)));
//					cal1.setResidualInterest(df.format(2.02));
//					list.add(cal1);
//					cal.setList(list);
//				}
//				//回收总金额
//				cal.setAmount(df.format(totleTenderMonet));
//				//月利率
//				cal.setRate(df.format(vo.getYearRate()/12));
//				//总回收利息
//				cal.setTotleInterest(df.format(totleInterest));
//				cal.setPeriod(vo.getPeriod());
//				cal.setPeriodUnit(vo.getPeriodUnit());
//			}
			//等额本息
			if(vo.getInterestMethod() == 3){
				//每月应还总金额
				Double tenderAmount= 
						(vo.getMoney()*(vo.getYearRate()/12/100)*(Math.pow((1+vo.getYearRate()/12/100), vo.getPeriod())))/(Math.pow((1+vo.getYearRate()/12/100), vo.getPeriod())-1);
				Double tenderTotleMoney = 0.00;//已还本金
				Double tenderTotleInterest = 0.00;//已还利息
				List<Calculator> list = new ArrayList<Calculator>();
				for(int i=1;i<=vo.getPeriod();i++ ){
					Calculator cal1 = new Calculator();
					//每月应还的本金
					Double tenderMoney = vo.getMoney()*(vo.getYearRate()/12/100)*(Math.pow((1+vo.getYearRate()/12/100), i-1))/(Math.pow((1+vo.getYearRate()/12/100), vo.getPeriod())-1);
					tenderTotleMoney += tenderMoney;
					//每月应还利息
					Double tenderInterest =  tenderAmount - tenderMoney ;
					tenderTotleInterest += tenderInterest ;
					cal1.setIndex(i);
					cal1.setTotleAmount(df.format(tenderAmount));
					cal1.setTotleMoney(df.format(tenderMoney));
					cal1.setInterest(df.format(tenderInterest));
					cal1.setIncome(df.format(tenderInterest));
					cal1.setResidualAmount(df.format(vo.getMoney()-tenderTotleMoney));
					cal1.setResidualInterest(df.format(tenderAmount*vo.getPeriod()-vo.getMoney()-tenderTotleInterest));
					list.add(cal1);
					cal.setList(list);
				}
				//回收总金额
				cal.setAmount(df.format(tenderTotleMoney+tenderTotleInterest));
				//月利率
				cal.setRate(df.format(vo.getYearRate()/12));
				//总回收利息
				cal.setTotleInterest(df.format(tenderTotleInterest));
				cal.setPeriod(vo.getPeriod());
				cal.setPeriodUnit(vo.getPeriodUnit());
			}
			//每月付息，到期还本
			if(vo.getInterestMethod() == 4){
				List<Calculator> list = new ArrayList<Calculator>();
				Double totleInterest = 0.00;//累计还款利息
				for(int i=1;i<=vo.getPeriod();i++ ){
					Calculator cal1 = new Calculator();
					//每月应还利息
					Double tenderInterest =  vo.getMoney()*vo.getYearRate()/12/100 ;
					totleInterest += tenderInterest;
					cal1.setIndex(i);
					if(i==vo.getPeriod()){
						cal1.setTotleAmount(df.format(tenderInterest+vo.getMoney()));
						cal1.setTotleMoney(df.format(vo.getMoney()));
						cal1.setInterest(df.format(tenderInterest));
						cal1.setIncome(df.format(tenderInterest));
						cal1.setResidualAmount("0.00");
						cal1.setResidualInterest("0.00");
					}else{
						cal1.setTotleAmount(df.format(tenderInterest));
						cal1.setTotleMoney("0.00");
						cal1.setInterest(df.format(tenderInterest));
						cal1.setIncome(df.format(tenderInterest));
						cal1.setResidualAmount(df.format(vo.getMoney()));
						cal1.setResidualInterest(df.format(tenderInterest*vo.getPeriod()-tenderInterest*i));
					}
					list.add(cal1);
					cal.setList(list);
				}
				//回收总金额
				cal.setAmount(df.format(totleInterest+vo.getMoney()));
				//月利率
				cal.setRate(df.format(vo.getYearRate()/12));
				//总回收利息
				cal.setTotleInterest(df.format(totleInterest));
				cal.setPeriod(vo.getPeriod());
				cal.setPeriodUnit(vo.getPeriodUnit());
			}
		}else{
			List<Calculator> list = new ArrayList<Calculator>();
			Calculator cal1 = new Calculator();
			cal1.setIndex(1);
			cal1.setTotleAmount(df.format(vo.getMoney()*vo.getYearRate()/12/100/30*vo.getPeriod()+vo.getMoney()));
			cal1.setTotleMoney(df.format(vo.getMoney()));
			cal1.setInterest(df.format(vo.getMoney()*vo.getYearRate()/12/100/30*vo.getPeriod()));
			cal1.setIncome(df.format(vo.getMoney()*vo.getYearRate()/12/100/30*vo.getPeriod()));
			cal1.setResidualAmount("0.00");
			cal1.setResidualInterest("0.00");
			list.add(cal1);
			cal.setList(list);
			
			//回收总金额
			cal.setAmount(df.format(vo.getMoney()*vo.getYearRate()/12/100/30*vo.getPeriod()+vo.getMoney()));
			//月利率
			cal.setRate(df.format(vo.getYearRate()/12));
			//总回收利息
			cal.setTotleInterest(df.format(vo.getMoney()*vo.getYearRate()/12/100/30*vo.getPeriod()));
			cal.setPeriod(vo.getPeriod());
			cal.setPeriodUnit(vo.getPeriodUnit());
		}
		return cal;
	}
	
	/**
	 * 随机hash值
	 * @return
	 */
	public static String randomHash(){
		String hash="";
		String chars = "abcdefghijklmnopqrstuvwxyz";
		for (int i = 0; i < 6; i++) {
			hash=hash+chars.charAt((int)(Math.random() * 26))+"";
		}
		return hash;
	}
	
	/*public static void main(String[] args) {
		BaseUtil util=new BaseUtil();
		System.out.println(util.generatePaymentRecord(2, 5000.00, 0.15, 2,new Date(),"DAY"));
	}*/
	public static void main(String[] args) {
		System.out.println(getInterestByType(1, 100000.0, 0.12, 15, "DAY"));
	}
}
